﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Navigation;
using GranitePackageSystem.GranitePackagingService;

namespace GranitePackageSystem.Views.Request
{
    public partial class PackageDetails : Page
    {
        private int _errorCount = 0;

        private GranitePackagingService.Request currentRequest = new GranitePackagingService.Request();
        private Package internalPkg;
        public PackageDetails()
        {
            InitializeComponent();
        }

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            if (App.Current.Resources.Contains("Current Request")) 
            { 
                currentRequest = App.Current.Resources["Current Request"] as GranitePackagingService.Request;
                DateTime MIN_SQL_DATE = (DateTime)App.Current.Resources["Min SQL Date"];
                if (currentRequest.VirtStepComplete.CompareTo(MIN_SQL_DATE) > 0)
                {

                    checkRoles();
                    updateRequestNavTable();

                    switch (currentRequest.Status)
                    {
                        case "Package Configured":
                            panelARPBrowser.Visibility = System.Windows.Visibility.Collapsed;
                            panelLoadButton.Visibility = System.Windows.Visibility.Collapsed;

                            panelPackageSaved.Visibility = System.Windows.Visibility.Visible;
                            btnNext.IsEnabled = true;
                            btnNext.Visibility = System.Windows.Visibility.Visible;
                            busyIndicatorPackage.IsBusy = false;
                            break;
                        default:
                            break;
                    }

                    busyIndicatorPackage.IsBusy = true;
                }
                else
                {
                    this.NavigationService.Navigate(new Uri("/Home", System.UriKind.Relative)); 
                }
            }
            else 
            { 
                this.NavigationService.Navigate(new Uri("/Home", System.UriKind.Relative)); 
            }
        }
        private void updateRequestNavTable()
        {
            DateTime MIN_SQL_DATE = (DateTime)App.Current.Resources["Min SQL Date"];
            if (App.Current.Resources.Contains("Current Request"))
            {
                expanderRequest.Visibility = System.Windows.Visibility.Visible;
                if (currentRequest.Stage.Equals("Staging"))
                {
                    linkTestingDetails.Visibility = System.Windows.Visibility.Visible;
                    if (currentRequest.VirtStepComplete.CompareTo(MIN_SQL_DATE) > 0)
                    {
                        linkPackageDetails.Visibility = System.Windows.Visibility.Visible;
                        if (currentRequest.PackageStepComplete.CompareTo(MIN_SQL_DATE) > 0)
                        {
                            linkLicensingDetails.Visibility = System.Windows.Visibility.Visible;
                            if (currentRequest.LicensingStepComplete.CompareTo(MIN_SQL_DATE) > 0)
                            {
                                linkSummaryDetails.Visibility = System.Windows.Visibility.Visible;
                            }
                            else
                            {
                                linkSummaryDetails.Visibility = System.Windows.Visibility.Collapsed;
                            }
                        }
                        else
                        {
                            linkLicensingDetails.Visibility = System.Windows.Visibility.Collapsed;
                            linkSummaryDetails.Visibility = System.Windows.Visibility.Collapsed;
                        }
                    }
                    else
                    {
                        linkPackageDetails.Visibility = System.Windows.Visibility.Collapsed;
                        linkLicensingDetails.Visibility = System.Windows.Visibility.Collapsed;
                        linkSummaryDetails.Visibility = System.Windows.Visibility.Collapsed;
                    }
                }
                else
                {
                    linkLicensingDetails.Visibility = System.Windows.Visibility.Collapsed;
                    linkPackageDetails.Visibility = System.Windows.Visibility.Collapsed;
                    linkTestingDetails.Visibility = System.Windows.Visibility.Collapsed;
                    linkSummaryDetails.Visibility = System.Windows.Visibility.Visible;
                }
            }
        }
        private void checkRoles()
        {
            Web.User user = WebContext.Current.User;
            bool userInARole = false;

            if (user.IsInRole("GENMILLS\\GPS_Requesters")) { userInARole = true; }
            if (user.IsInRole("GENMILLS\\GPS_Administrators")) { userInARole = true; }
            if (user.IsInRole("GENMILLS\\GPS_LicensingApprovers")) { userInARole = true; }
            if (user.IsInRole("GENMILLS\\GPS_DeploymentApprovers")) { userInARole = true; }

            if (userInARole) {  }
            else { this.NavigationService.Navigate(new System.Uri("/Unauthorized", System.UriKind.Relative)); }
        }

        void proxy_getNewARPEntriesCompleted(object sender, getNewARPEntriesCompletedEventArgs e)
        {
            if (e.Result.Count > 0)
            {
                busyIndicatorPackage.IsBusy = false;
                RegistryEntryList.ItemsSource = e.Result;
                panelContent.Visibility = System.Windows.Visibility.Visible;
                panelARPBrowser.Visibility = System.Windows.Visibility.Visible;
                btnUseSelected.Visibility = System.Windows.Visibility.Visible;
                panelPackageInformation.Visibility = System.Windows.Visibility.Visible;

                busyIndicatorPackage.IsBusy = false;
                
                btn_LoadData.IsEnabled = true;
            }
            else
            {
                MessageBox.Show("No new ARP Entries found, please install software and try again or enter manually");
                busyIndicatorPackage.IsBusy = false;
                RegistryEntryList.ItemsSource = e.Result;
                panelContent.Visibility = System.Windows.Visibility.Visible;
                panelARPBrowser.Visibility = System.Windows.Visibility.Visible;
                btnUseSelected.Visibility = System.Windows.Visibility.Collapsed;
                panelPackageInformation.Visibility = System.Windows.Visibility.Visible;

                busyIndicatorPackage.IsBusy = false;
                btn_LoadData.IsEnabled = true;

                boxPackageSourceFileHash.Text = "AUTO GENERATED";
                boxPackageSourceFileHash.IsReadOnly = true;
                boxPackageSourceFileLocation.Text = "AUTO GENERATED";
                boxPackageSourceFileLocation.IsReadOnly = true;
                btnSavePackageDetails.IsEnabled = true;
                btnSavePackageDetails.Visibility = System.Windows.Visibility.Visible;
            }
        }

        private void btnUseSelected_Click(object sender, RoutedEventArgs e)
        {
            if (RegistryEntryList.SelectedItem != null)
            {
                Models.packageInfo packInfo = new Models.packageInfo();
                
                if (((RegistryEntry)RegistryEntryList.SelectedItem).DisplayName != null)
                {
                    try { packInfo.PackageName = ((RegistryEntry)RegistryEntryList.SelectedItem).DisplayName.ToString(); }
                    catch {  }
                }
                if (((RegistryEntry)RegistryEntryList.SelectedItem).Publisher != null)
                {
                    try { packInfo.PackagePublisher = ((RegistryEntry)RegistryEntryList.SelectedItem).Publisher.ToString(); }
                    catch {  }
                }
                if (((RegistryEntry)RegistryEntryList.SelectedItem).Version != null)
                {
                    try { packInfo.PackageVersion = ((RegistryEntry)RegistryEntryList.SelectedItem).Version.ToString(); }
                    catch {  }
                }
                if (((RegistryEntry)RegistryEntryList.SelectedItem).EstimatedSize != null)
                {
                    try { packInfo.PackageSize = ((RegistryEntry)RegistryEntryList.SelectedItem).EstimatedSize.ToString(); }
                    catch { }
                }
                if (((RegistryEntry)RegistryEntryList.SelectedItem).UninstallString != null)
                {
                    try { packInfo.PackageUninstallString = ((RegistryEntry)RegistryEntryList.SelectedItem).UninstallString.ToString(); }
                    catch { }
                }

                boxPackageName.DataContext = packInfo;
                boxPackagePublisher.DataContext = packInfo;
                boxPackageVersion.DataContext = packInfo;
                boxPackageSize.DataContext = packInfo;
                boxUninstallString.DataContext = packInfo;
            }
            else
            {
                MessageBox.Show("Select an Entry");
            }
            panelPackageInformation.Visibility = Visibility.Visible;

            boxPackageSourceFileHash.Text = "AUTO GENERATED";
            boxPackageSourceFileHash.IsReadOnly = true;
            boxPackageSourceFileLocation.Text = "AUTO GENERATED";
            boxPackageSourceFileLocation.IsReadOnly = true;
            btnSavePackageDetails.IsEnabled = true;
            btnSavePackageDetails.Visibility = System.Windows.Visibility.Visible;
        }
        private void btn_LoadData_Click(object sender, RoutedEventArgs e)
        {
            image.Source = new BitmapImage(new Uri("/GranitePackageSystem;component/Assets/Resources/ARPSelect.png", UriKind.RelativeOrAbsolute));
            busyIndicatorPackage.IsBusy = true;
            busyIndicatorPackage.BusyContent = "Loading ARP Data";
            btn_LoadData.IsEnabled = false;
            GranitePackagingServiceSoapClient proxy = new GranitePackagingServiceSoapClient();
            proxy.InnerChannel.OperationTimeout = new TimeSpan(0, 10, 0);
            proxy.getRequestVirtualMachineCompleted += new EventHandler<getRequestVirtualMachineCompletedEventArgs>(proxy_getRequestVirtualMachineCompleted);
            proxy.getRequestVirtualMachineAsync(currentRequest);
        }
        void proxy_getRequestVirtualMachineCompleted(object sender, getRequestVirtualMachineCompletedEventArgs e)
        {
            GranitePackagingServiceSoapClient proxy = new GranitePackagingServiceSoapClient();
            proxy.InnerChannel.OperationTimeout = new TimeSpan(0, 10, 0);
            proxy.getNewARPEntriesCompleted += new EventHandler<getNewARPEntriesCompletedEventArgs>(proxy_getNewARPEntriesCompleted);
            proxy.getNewARPEntriesAsync(e.Result.Name, currentRequest.ARPList_32, currentRequest.ARPList_64);
        }
        private void btnSavePackageDetails_Click(object sender, RoutedEventArgs e)
        {
            if (_errorCount == 0 && !(boxPackageName.Text.Equals(String.Empty) || boxPackagePublisher.Text.Equals(String.Empty) || boxPackageVersion.Text.Equals(String.Empty)))
            {
                busyIndicatorPackage.IsBusy = true;
                busyIndicatorPackage.BusyContent = "Saving Package Information";

                GranitePackagingServiceSoapClient proxy = new GranitePackagingServiceSoapClient();
                proxy.getPackageListCompleted += new EventHandler<getPackageListCompletedEventArgs>(proxy_getPackageListCompleted_SavePackage);
                proxy.getPackageListAsync(currentRequest);
            }
            else
            {
                MessageBox.Show("Invalid Package Data");
            }
        }

        void proxy_getPackageListCompleted_SavePackage(object sender, getPackageListCompletedEventArgs e)
        {
            GranitePackagingServiceSoapClient proxy = new GranitePackagingServiceSoapClient();
            if (e.Result.Count > 0)
            {
                Package pkg = e.Result[0];
                pkg.Comment = boxPackageComments.Text;
                pkg.Name = boxPackageName.Text;
                pkg.Publisher = boxPackagePublisher.Text;
                pkg.Version = boxPackageVersion.Text;
                internalPkg = pkg;

                proxy.savePackageCompleted += new EventHandler<savePackageCompletedEventArgs>(proxy_savePackageCompleted_SavePackage);
                proxy.savePackageAsync(pkg);
            }
        }
        void proxy_savePackageCompleted_SavePackage(object sender, savePackageCompletedEventArgs e)
        {
            GranitePackagingServiceSoapClient proxy = new GranitePackagingServiceSoapClient();
            proxy.getProgramListCompleted += new EventHandler<getProgramListCompletedEventArgs>(proxy_getProgramListCompleted_SavePackage);
            proxy.getProgramListAsync(e.Result);
        }
        void proxy_getProgramListCompleted_SavePackage(object sender, getProgramListCompletedEventArgs e)
        {
            if (e.Result.Count > 0)
            {
                Program prg = e.Result[0];
                prg.uninstallString = boxUninstallString.Text;
                GranitePackagingServiceSoapClient proxy = new GranitePackagingServiceSoapClient();
                proxy.saveProgramCompleted += new EventHandler<saveProgramCompletedEventArgs>(proxy_saveProgramCompleted_SavePackage);
                proxy.saveProgramAsync(prg);
            }
        }
        void proxy_saveProgramCompleted_SavePackage(object sender, saveProgramCompletedEventArgs e)
        {
            currentRequest.Status = "Package Configured";
            currentRequest.PackageStepComplete = DateTime.UtcNow;
            App.Current.Resources.Remove("Current Request");
            App.Current.Resources.Add("Current Request", currentRequest);

            GranitePackagingServiceSoapClient proxy = new GranitePackagingServiceSoapClient();
            proxy.saveRequestCompleted += new EventHandler<saveRequestCompletedEventArgs>(proxy_saveRequestCompleted_SavePackage);
            proxy.saveRequestAsync(currentRequest);
        }
        void proxy_saveRequestCompleted_SavePackage(object sender, saveRequestCompletedEventArgs e)
        {
            panelARPBrowser.Visibility = System.Windows.Visibility.Collapsed;
            panelLoadButton.Visibility = System.Windows.Visibility.Collapsed;
            panelPackageInformation.Visibility = System.Windows.Visibility.Collapsed;
            btnUseSelected.Visibility = System.Windows.Visibility.Collapsed;
            btnSavePackageDetails.Visibility = System.Windows.Visibility.Collapsed;

            panelPackageSaved.Visibility = System.Windows.Visibility.Visible;
            btnNext.IsEnabled = true;
            btnNext.Visibility = System.Windows.Visibility.Visible;

            updateRequestNavTable();
            busyIndicatorPackage.IsBusy = false;

            this.NavigationService.Navigate(new Uri("/Request/Licensing", UriKind.Relative));
        }

        private void btnModifyPackageData_Click(object sender, RoutedEventArgs e)
        {
            panelARPBrowser.Visibility = System.Windows.Visibility.Collapsed;
            panelLoadButton.Visibility = System.Windows.Visibility.Visible;
            panelPackageInformation.Visibility = System.Windows.Visibility.Collapsed;
            btnUseSelected.Visibility = System.Windows.Visibility.Collapsed;

            panelPackageSaved.Visibility = System.Windows.Visibility.Collapsed;
            btnNext.Visibility = System.Windows.Visibility.Collapsed;
        }

        private void btnNext_Click(object sender, RoutedEventArgs e)
        {
            this.NavigationService.Navigate(new Uri("/Request/Licensing", UriKind.Relative));
        }

        private void boxPackageVersion_BindingValidationError(object sender, ValidationErrorEventArgs e)
        {
            if (e.Action == ValidationErrorEventAction.Added)
                _errorCount++;
            else if (e.Action == ValidationErrorEventAction.Removed)
                _errorCount--;
        }

        private void boxPackageName_BindingValidationError(object sender, ValidationErrorEventArgs e)
        {
            if (e.Action == ValidationErrorEventAction.Added)
                _errorCount++;
            else if (e.Action == ValidationErrorEventAction.Removed)
                _errorCount--;
        }

        private void boxPackagePublisher_BindingValidationError(object sender, ValidationErrorEventArgs e)
        {
            if (e.Action == ValidationErrorEventAction.Added)
                _errorCount++;
            else if (e.Action == ValidationErrorEventAction.Removed)
                _errorCount--;
        }
    }
}
